from flask import request, redirect, flash, render_template, url_for,Blueprint,g,current_app
from app.exts import db
from flask_login import login_user, login_required, logout_user, current_user
from flask import session

from . import auth_bp

from app.forms import LoginForm,RegistrationForm
from app.models import User

import logging

# 获取日志记录器
logger = logging.getLogger(__name__)

'''
蓝图在国际化中的使用比较多：http://www.bjhee.com/flask-ad6.html

这个@lang_bp.url_value_preprocessor装饰器表明,它所装饰的函数,会在视图函数被调用之前,
URL路径被预处理时执行。而且只针对当前蓝图的所有视图有效。它所传入的第二个参数,
保存了当前请求URL路径上的所有参数的值。所以上面的get_lang_code_from_url()
函数就可以在URL预处理时,设置g.lang_code变量。这样视图函数中就可以取到g.lang_code,
而我们的程序也能够正常运行了。
'''
# @login_bp.url_value_preprocessor
# def get_lang_code_from_url(endpoint, view_args):
#     g.lang_code = view_args.pop('lang_code')

@auth_bp.route('/', methods=['GET', 'POST'])
def index():
    # TODO:# bootstrap4: mybase2.html
    logger.info('---------------------->index')
    uid = session.get('username', None)
    print(f'uid---index={uid}')
    
    if uid: # uid存在与session，则直接登录
        user = User.query.filter_by(username=uid).first()
        g.user = user
        print(f'user----------2={user}')
        return render_template('auth/index.html', user=user)
    else:
        return render_template('auth/index.html') # 继承bootstrap的html模板


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    logger.info('---------------------->login')
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        print(f'username={username},password={password}')
        session['username'] = username
        user = User.query.filter_by(username=username).first()
        return redirect(url_for('auth.index'))
        # if user and user.check_password(password):  # 假设你有一个 check_password 方法
        #     flash('Logged in successfully.')            
        # else:
        #     flash('Invalid username or password.')
    return render_template('auth/index.html')
    

 
    # if request.method == 'POST':
    #     username = request.form['username']
    #     password = request.form['password']
    #     user = User.query.filter_by(username=username).first()
    #     if user and user.verify_password(password):  # 假设你有一个 verify_password 方法
    #         print('-->Logged in successfully.')
    #         return redirect(url_for('main.login'))
    #     else:
    #         render_template('auth/register.html')
    # else:
    #     return render_template('auth/register.html')


    
@auth_bp.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        repassword = request.form['repassword']
        session['username'] = username
        print(username, password,repassword)
        new_user = User(username=username, password=password)  # 假设你有一个 set_password 方法
        db.session.add(new_user)
        db.session.commit()
        # flash('Registration successful.')
        # return redirect(url_for('auth.login'))
        return "注册成功"
    return render_template('auth/index.html')
    
@auth_bp.route('/logout')
def logout():
    # 假设你有一个 logout_user 函数
    session.pop('username',None) # 删除用户
    return redirect(url_for('auth.index'))
# -------------------------------分割线---------------------------
@auth_bp.route('/login2',methods=['GET','POST'])
def login2():    
    form = LoginForm()
    if form.validate_on_submit():
        return '登录成功'
    return render_template('auth/login2.html',form=form)

# TODO:bootstrap的测试页面   
@auth_bp.route('/index2',methods=['GET','POST']) 
def index2():
    return render_template('auth/index2.html')

# def login():
    # form = LoginForm()
    # if form.validate_on_submit():
    #     name = form.name.data
    #     flask.session['name'] = name
    #     flash(f"Welcome {name}!")
    #     return redirect(url_for('todo.index'))
    # return render_template('login.html',form=form)